package util

import (
	"fmt"
	"os"
	"time"
)

const (
	// LevelError 错误
	LevelError = iota
	// LevelWarning 警告
	LevelWarning
	// LevelInformational 提示
	LevelInformational
	// LevelDebug 除错
	LevelDebug
)

var logger *Logger

type Logger struct {
	level int
}

// Println 打印
func (c *Logger) Println(msg string) {
	fmt.Printf("\033[94m %s %s \033[0m\n", time.Now().Format("2006-01-02 15:04:05 -0700"), msg)
}

// Panic 极端错误
func (c *Logger) Panic(format string, v ...interface{}) {
	if LevelError > c.level {
		return
	}
	msg := fmt.Sprintf("[Panic] "+format, v...)
	c.Println("\033[91m" + msg + "\033[0m\n")
	os.Exit(0)
}

// Error 错误
func (c *Logger) Error(format string, v ...interface{}) {
	if LevelError > c.level {
		return
	}
	msg := fmt.Sprintf("[E] "+format, v...)
	c.Println("\033[91m" + msg + "\033[0m\n")
}

// Warning 警告
func (c *Logger) Warning(format string, v ...interface{}) {
	if LevelWarning > c.level {
		return
	}
	msg := fmt.Sprintf("[W] "+format, v...)
	c.Println("\033[94m" + msg + "\033[0m\n")
}

// Info 信息
func (c *Logger) Info(format string, v ...interface{}) {
	if LevelInformational > c.level {
		return
	}
	msg := fmt.Sprintf("[I] "+format, v...)
	c.Println("\033[93m" + msg + "\033[0m\n")
}

// Debug 校验
func (c *Logger) Debug(format string, v ...interface{}) {
	if LevelDebug > c.level {
		return
	}
	msg := fmt.Sprintf("[D] "+format, v...)
	c.Println("\033[92m" + msg + "\033[0m\n")
}

func BuildLogger(level string) {
	intLevel := LevelError
	switch level {
	case "error":
		intLevel = LevelError
	case "warning":
		intLevel = LevelWarning
	case "info":
		intLevel = LevelInformational
	case "debug":
		intLevel = LevelDebug
	}

	logger = &Logger{
		level: intLevel,
	}
}

// Log 返回日志对象
func Log() *Logger {
	if logger == nil {
		logger = &Logger{
			level: LevelDebug,
		}
	}
	return logger
}
